<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'e.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
<script type="text/javascript">
	function createXMLHttpRequest() {
		try {
			return new XMLHttpRequest();
		} catch (e) {
			try {
				return new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					return new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {
					alter("浏览器不兼容！");
					throw e;
				}
			}
		}
	}

	window.onload = function() {
		var province = document.getElementById("province");
		var xmlHttp = createXMLHttpRequest();
		xmlHttp.open("GET", "<c:url value='/ajax/ProvinceServlet'/>", true);
		xmlHttp.send(null);
		xmlHttp.onreadystatechange = function() {
			if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
				var content = xmlHttp.responseText;
				var arr = content.split(",");
				for ( var i = 0; i < arr.length; i++) {
					var op = document.createElement("option");
					var textNode = document.createTextNode(arr[i]);
					op.append(textNode);
					op.value = arr[i];
					province.appendChild(op);
				}
			}
		};

		var city = document.getElementById("city");
		province.onchange = function() {
			xmlHttp.open("POST", "<c:url value='/ajax/CityServlet'/>", true);
			xmlHttp.setRequestHeader("Content-Type",
					"application/x-www-form-urlencoded");
			xmlHttp.send("province=" + province.value);
			xmlHttp.onreadystatechange = function() {
				if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
					// 删除除了“请选择”以外的option
					var opts = city.getElementsByTagName("option");
					while (opts.length > 1) {
						city.removeChild(opts[1]);
					}

					var doc = xmlHttp.responseXML;
					var cityEles = doc.getElementsByTagName("city");
					for ( var i = 0; i < cityEles.length; i++) {
						var cityName;
						// 浏览器差异：window.addEventListener —— 不为IE
						if (window.addEventListener) {
							cityName = cityEles[i].textContent;
						} else {
							cityName = cityEles[i].text;
						}
						var op = document.createElement("option");
						var textNode = document.createTextNode(cityName);
						op.append(textNode);
						op.value = cityName;
						city.appendChild(op);
					}
				}
			};
		};
	};
</script>
</head>

<body>
	<h1>AJAX 省市联动 XML</h1>
	<select name="province" id="province">
		<option>==请选择省份==</option>
	</select>
	<select name="city" id="city">
		<option>==请选择城市==</option>
	</select>
</body>
</html>
